package com.cavy.platform.server.domain.job;

import com.cavy.platform.server.service.ContainerLogTailerManager;
import lombok.Data;

import javax.websocket.Session;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Data
public class ContainerLogUnSubscribeKey extends ContainerLogSubscribeKey {
    public ContainerLogUnSubscribeKey(String workSpace, String project, String pipeline, String number
            , String stage, int containerIndex, int dependencyIndex) {
        super(workSpace, project, pipeline, number, stage, containerIndex, dependencyIndex);
        type = "unsubscribe";
    }

    public ContainerLogUnSubscribeKey() {
    }

    public ContainerLogUnSubscribeKey(ContainerLogSubscribeKey key) {
        super(key.getWorkSpace(), key.getProject(), key.getPipeline(), key.getNumber(), key.getStage(), key.getContainerIndex(), key.getDependencyIndex());
        type = "unsubscribe";
    }

    @Override
    public void handler(ConcurrentHashMap<ContainerLogSubscribeKey, List<Session>> subscribe, Session session, ContainerLogTailerManager tailerManager) {
        List<Session> sessions = subscribe.get(this);
        if (sessions == null) {
            return;
        }
        if (sessions.isEmpty()) {
            subscribe.remove(this);
            tailerManager.destroy(this);
        } else {
            sessions.remove(session);
            subscribe.put(this, sessions);
        }
    }
}
